package com.novel.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

/**
 *	json工具类 
 * @author Administrator
 */
public class JsonUtil
{
    public static Map<String, String[]> getRequestMap(HttpServletRequest request)
            throws Exception
        {
            Map<String, String[]> map = request.getParameterMap();
            if(request.getMethod().equals("POST"))
            {
                request.setCharacterEncoding("UTF-8");
            } else
            {
                Map<String, String[]> utf8map = new HashMap<String, String[]>();
                String key;
                String utf8values[];
                for(Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext(); utf8map.put(key, utf8values))
                {
                    key = (String)iterator.next();
                    String values[] = (String[])map.get(key);
                    utf8values = new String[values.length];
                    for(int i = 0; i < values.length; i++)
                        utf8values[i] = new String(values[i].getBytes("ISO-8859-1"), "UTF-8");
                }

                map = utf8map;
            }
            return map;
        }

        public static Object request2Domain(HttpServletRequest request, Class<?> beanClass)
            throws Exception
        {
            Object bean = beanClass.newInstance();
            Map<String, String[]> map = getRequestMap(request);
            BeanUtils.populate(bean, map);
            return bean;
        }
}
